<template>
    <div ref="chart" style="height: 180px;"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { type EChartsOption } from 'echarts'
import { onMounted, ref } from 'vue';
import axios from 'axios';
let chart = ref<HTMLElement | null>(null)
let option: EChartsOption = {
    xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
    },
    yAxis: {
        type: 'category',
        data: [],
    },
    grid: {
        height: 140,
        top: 15
    },
    series: []
};
//实例
let myEchats: echarts.ECharts | null = null
function init() {
    myEchats = echarts.init(chart.value)
    myEchats.setOption(option)
    getData()
}
//保留接口原有数据
let original: any = {}
function getData() {
    // axios.get('/api/seller.json').then(({ data }) => {
    //     console.log(data);
    //     original = data
    //     changeOption()
    // })

    const ws = new WebSocket("ws://localhost:9998")
    ws.onopen = () => {
        console.log("Connect success!")

        ws.onmessage = (res) => {
            let a = JSON.parse(res.data)
            let b = JSON.parse(a.data)
            original = b
            changeOption()
        }

        ws.send(JSON.stringify({
            action: "getData",
            chartName: "seller"
        }))
    }
}
var iii = 0;
function changeOption() {
    iii = (iii + 1) % 3
    let displayData = [...original]
    switch (iii) {
        case 0:
            displayData = [...original]
                .sort((a, b) => a.value - b.value)
                .slice(0, 5);
            break;
        case 1:
            displayData = [...original]
                .sort((a, b) => a.value - b.value)
                .slice(5, 10);
            break;
        case 2:
            displayData = [...original]
                .sort((a, b) => a.value - b.value)
                .slice(10, 15);
            break;
    }
    option.series = [];
    (option.yAxis as any).data = [];
    (option.yAxis as any).data = displayData.map((item: any) => item.name);
    (option.series as any).push({
        realtimeSort: false,
        // name: displayData.map((item: any) => item.name),
        type: 'bar',
        data: displayData.map((item: any) => item.value),
        label: {
            show: true,
            position: 'right',
            valueAnimation: true
        }
    });
    myEchats?.setOption(option)
}

function debounce(func: any, wait: number) {
    let timeout: number | undefined
    return function (this: any, ...args: any[]) {
        const context: any = this;
        clearTimeout(timeout)
        timeout = setTimeout(() => func.apply(context, args), wait)
    }
}
let timer: number | null = null;
onMounted(() => {
    init()
    window.addEventListener('resize', debounce(() => {
        myEchats?.resize()
    }, 100))
    timer = window.setInterval(() => {
        changeOption();
    }, 3000);
})
</script>

<style scoped></style>